
from django.contrib.contenttypes.fields import  GenericRelation
from django.contrib.contenttypes.models import ContentType

# Create your models here.
from django.utils import timezone

from apps.common.models import *
from apps.common.models import PbiInfoBaseModel, OpocBaseModel
from apps.system.models import Check
from extensions.common.base import *
from extensions.models import *


class Client(PbiBaseModel):
    """客户发包方"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, null=True, default=None,related_name='Client_company')  # 填报公司
    profile = CharField(max_length=256, null=True, blank=True, verbose_name='客户简介')# 客户简介
    cooperation_methods = JSONField(blank=True, default=None, verbose_name='合作方式') # 合作方式
    client_property = ForeignKey('system.Dict_item', on_delete=CASCADE, verbose_name='客户属性',blank=True,related_name='Client_client_property')# 客户属性
    region = JSONField(null=True, blank=True, default=None, verbose_name='区县')
    industry_types = JSONField(blank=True,default=None, verbose_name='行业类型') # 行业类型
    evaluate = CharField(max_length=256, null=True, blank=True, verbose_name='客户评价')
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,verbose_name='创建者',related_name='Client_creator')
    updater = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,verbose_name='更新者',related_name='Client_updater')
    next_checker = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,related_name='Client_next_checker')  # 下一步审核或操作的人
    address = CharField(max_length=256, null=True, blank=True, verbose_name='地址')
    checks = GenericRelation(Check)

    class Meta:
        unique_together = [('number', 'name'),]
        indexes =[Index(fields=['company','creator','updater','next_checker'])]


class ClientCheck(PbiBaseCheck):
    """客户信息填报审核记录"""
    check_user = ForeignKey('system.User', on_delete=SET_NULL,null=True,blank=True, default=None,
                            related_name='ClientCheck_check_user')
    client = ForeignKey(Client, on_delete=CASCADE,null=True, blank=True, default=None, related_name='ClientChecks_client')

    class Meta:
        verbose_name = '客户信息填报审核记录'
        verbose_name_plural = verbose_name

    def __int__(self):
        return self.id


class SupplierManufactor(PbiBaseModel):
    """供应商厂家"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, null=True, default=None,
                         related_name='SupplierManufactor_company')  # 填报公司
    accounting_period = IntegerField(null=True, blank=True, verbose_name='账期')
    credit_limit = FloatField(null=True, blank=True, verbose_name='信用额度')
    product_specialty = JSONField(blank=True,default=None, verbose_name='产品覆盖专业')
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='创建者',
                         related_name='SupplierManufactor_creator')
    updater = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='更新者',
                         related_name='SupplierManufactor_updater')
    next_checker = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,
                              related_name='SupplierManufactor_next_checker')  # 下一步审核或操作的人
    checks = GenericRelation(Check)

    class Meta:
        unique_together = [('number', 'name'),]
        indexes = [Index(fields=['company','next_checker'])]


class Pbi_Common_Pdfs(Model):
    """PBI通用pdf"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None,
                         related_name='Pbi_Common_Pdfs_company')
    file = FileField(max_length=256, upload_to='pbi_common_pdf/',verbose_name='文件')
    name = CharField(max_length=256, verbose_name='文件名称')
    type = CharField(max_length=256, verbose_name='文件类型',help_text='文件类型')#1 集成商营业执照附件2=集成商营业资质附件
    del_flag = BooleanField(verbose_name='删除标识', default=False)
    remarks = CharField(max_length=255, verbose_name='备注', null=True, blank=True)
    creator = ForeignKey('system.User', on_delete=SET_NULL,null=True, blank=True, default=None,
                           related_name='Pbi_Common_Pdfs_creator')  # 填报人
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)


class SupplierIntegrator(PbiBaseModel):
    """供应商集成商"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, null=True, default=None,
                         related_name='SupplierIntegrator_company')  # 填报公司
    business_scope =CharField(max_length=1024, null=True, blank=True, verbose_name='营业范围')
    business_qualification =CharField(max_length=1024, null=True, blank=True, verbose_name='营业资质')
    #引入方式
    introduce_method = ForeignKey('system.Dict_item', on_delete=CASCADE, verbose_name='引入方式', blank=True,related_name='SupplierIntegrator_introduce_method')# 引入方式
    business_license_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                           related_name='SupplierIntegrator_business_license_pdf')  # 营业执照附件
    business_qualification_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                           related_name='SupplierIntegrator_business_qualification_pdf')  # 营业资质附件
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,
                           related_name='SupplierIntegrator_creator')  # 填报人
    updater = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='更新者',
                         related_name='SupplierIntegrator_updater')
    next_checker = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,
                              related_name='SupplierIntegrator_next_checker')  # 下一步审核或操作的人
    checks = GenericRelation(Check)

    class Meta:
        unique_together = [('number', 'name'),]
        indexes = [Index(fields=['company', 'updater', 'next_checker'])]


class ManufactorProduct(Model):
    """厂家产品"""
    company = ForeignKey('system.Company', on_delete=SET_NULL,null=True, blank=True, default=None, related_name='ManufactorProduct_company')#填报公司
    number = CharField(max_length=256, verbose_name='编号')
    name = CharField(max_length=256, verbose_name='产品名称')
    product_model = CharField(max_length=256,blank=True,null=True,  default=None, verbose_name='产品型号')
    product_price = FloatField(blank=True,null=True,  default=None, verbose_name='产品单价')
    product_specialty = JSONField(blank=True,default=None, verbose_name='产品覆盖专业')
    supplier_manufactor = ForeignKey('pbi.SupplierManufactor', on_delete=CASCADE, blank=True, default=None,
                                     related_name='ManufactorProduct_supplier_manufactor')#供应商厂家
    del_flag = BooleanField(default=False, null=True, blank=True, verbose_name='删除标志')  # 0=未删除1=已删除
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None,
                         related_name='ManufactorProduct_creator')  # 填报人
    updater = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='更新者',
                         related_name='ManufactorProduct_updater')
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)
    update_time = DateTimeField(auto_now=True, verbose_name='更新时间', null=True, blank=True)
    remark = CharField(max_length=256, null=True, blank=True, verbose_name='备注')

    class Meta:
        verbose_name = '厂家产品'
        verbose_name_plural = verbose_name
        indexes = [Index(fields=['company','supplier_manufactor','creator'])]

    def __str__(self):
        return self.name


# 审批流
class CheckFlow(Model):
    model = ForeignKey(ContentType, on_delete=CASCADE, blank=True, default=None, related_name='CheckFlow_model')
    name = CharField(max_length=256, verbose_name='名称', null=True, blank=True, default=None)
    steps = ManyToManyField('system.Role', blank=True, default=None, related_name='CheckFlow_steps')#审批步骤
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间',null=True, blank=True)

    class Meta:
        verbose_name = '审批流'
        verbose_name_plural = verbose_name


    def __str__(self):
        return self.name

# 商机管理
class BusinessOpportunity(PbiInfoBaseModel):
    """商机管理"""
    content = CharField(max_length=255, verbose_name='项目内容', null=True, blank=True)
    client = ForeignKey(Client, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='BusinessOpportunity_client',verbose_name='甲方单位')  # 通客户管理表外键关联
    is_frame = BooleanField(verbose_name='是否为框架合同', default=False)
    budget = FloatField(verbose_name='合同预算', null=True, blank=True, default=0)

    introduction_time = DateField(verbose_name='项目引入时间', null=True, blank=True)
    estimated_signing_time = DateField(verbose_name='项目预计签订时间', null=True, blank=True)
    signing_time = DateField(verbose_name='项目签订时间', null=True, blank=True)
    deadline = DateField(verbose_name='项目截止时间', null=True, blank=True)
    business_type = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                               default=None, related_name='BusinessOpportunity_business_type')  # 业务类型
    industry_type = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                               default=None, related_name='BusinessOpportunity_industry_type')  # 行业类型
    project_properties = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                                    default=None, related_name='BusinessOpportunity_project_properties')  # 项目属性
    project_source = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                                default=None, related_name='BusinessOpportunity_project_source')  # 项目来源
    project_status = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                                default=None, related_name='BusinessOpportunity_project_status')  # 项目状态
    business_opportunity_stage = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                                default=None, related_name='BusinessOpportunity_business_opportunity_stage')  # 商机阶段
    project_expansion_stage = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                                default=None, related_name='BusinessOpportunity_project_expansion_stage')  # 项目拓展阶段
    # status_change_record = ForeignKey('pbi_project_info.Status_change', on_delete=CASCADE, blank=True, default=None,related_name='projects')  # 项目状态变化记录1
    is_traction = BooleanField(verbose_name='是否牵引', default=False)
    traction_unit = ForeignKey(Client, on_delete=SET_NULL, null=True, blank=True,
                               default=None, related_name='BusinessOpportunity_traction_unit')  # 牵引单位
    development_responsible_person = ForeignKey('system.User', on_delete=SET_NULL, null=True, blank=True, default=None,
                                                related_name='BusinessOpportunity_development_responsible_person')  # 拓展责任人
    support_responsible_person = ForeignKey('system.User', on_delete=SET_NULL, null=True, blank=True, default=None,
                                            related_name='BusinessOpportunity_support_responsible_person')  # 支撑责任人
    #税率
    tax_rate = FloatField(verbose_name='税率', null=True, blank=True, default=0)
    #项目金额
    project_amount = FloatField(verbose_name='项目金额', null=True, blank=True, default=0)
    #预测签约时间
    forecast_signing_time = DateField(verbose_name='预测签约时间', null=True, blank=True, default=None)
    #签约预测者
    signing_forecast_person = ForeignKey('system.User', on_delete=SET_NULL, null=True, blank=True, default=None)#签约预测者
    #预测日期
    forecast_time = DateTimeField(verbose_name='预测时间', null=True, blank=True, default=None)
    progress_thisweek = CharField(max_length=255, verbose_name='本周进展', null=True, blank=True)
    #项目状态变化最后日期
    status_change_last_time = DateField(verbose_name='项目状态变化最后日期', null=True, blank=True, default=None)
    checks = GenericRelation(Check)

    class Meta:
        verbose_name = '商机管理'
        verbose_name_plural = verbose_name
        unique_together = [('number', 'name'),]
        indexes = [Index(fields=['company','next_checker'])]

    def save(self, *args, **kwargs):
        # 如果是新对象，将 status_change_last_time 设置为当前日期
        if self._state.adding:
            self.status_change_last_time = timezone.now().date()

        # 如果是更新对象，检查 project_status 是否发生变化
        else:
            old_instance = BusinessOpportunity.objects.get(pk=self.pk)
            if self.project_status != old_instance.project_status:
                self.status_change_last_time = timezone.now().date()

        super(BusinessOpportunity, self).save(*args, **kwargs)


class Contract_Common_Pdfs(OpocBaseModel):
    """签约合同管理pdf"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None,
                         related_name='Contract_Common_Pdfs_company')
    file = FileField(max_length=256, upload_to='contract_common_pdfs/',verbose_name='文件')
    name = CharField(max_length=256, verbose_name='文件名称')
    # type = IntegerField(verbose_name='文件类型')#1=合同扫描件2=项目评审表3=项目预算表 4=财务评审表 5=其它附件
    type = CharField(max_length=256,verbose_name='文件类型')#文件类型即是相应的附件字段名称
    creator = ForeignKey('system.User', on_delete=SET_NULL,null=True, blank=True, default=None,
                           related_name='Contract_Common_Pdfs_creator')  # 创建人
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)


# 签约合同管理
class Contract(PbiInfoBaseModel):
    """签约合同管理"""
    #商机
    business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, unique=True, blank=True, default=None,
                                      related_name='Contract_business_opportunity',
                                      error_messages={'unique': '该商机相应的签约合同已经存在了.'})

    # business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, unique=True,blank=True, default=None,related_name='Contract_business_opportunity')  # 商机
    region = JSONField(null=True, blank=True, default=None, verbose_name='区县')
    #签订日期
    signing_time = DateField(verbose_name='签订日期', null=True, blank=True, default=None)
    #合同金额含税
    contract_amount = FloatField(verbose_name='合同金额含税', null=True, blank=True, default=0)
    #合同金额不含税
    contract_amount_notax = FloatField(verbose_name='合同金额不含税', null=True, blank=True, default=0)
    #税率
    tax_rate = FloatField(verbose_name='税率', null=True, blank=True, default=0)
    #建设方单位名称
    construction_unit = CharField(max_length=255, verbose_name='建设方单位名称', null=True, blank=True)
    #实施地址
    implementation_address = CharField(max_length=255, verbose_name='实施地址', null=True, blank=True)
    #合同描述
    contract_description = CharField(max_length=255, verbose_name='合同描述', null=True, blank=True)
    #合同扫描件
    contract_scan_pdf = ForeignKey(Contract_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Contract_contract_scan_pdf')  # 合同扫描件
    #项目评审表
    project_review_form = ForeignKey(Contract_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Contract_project_review_form')  # 项目评审表
    #项目预算表
    project_budget_form = ForeignKey(Contract_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Contract_project_budget_form')  # 项目预算表
    #财务评审表
    financial_review_form = ForeignKey(Contract_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Contract_financial_review_formf')  # 财务评审表
    #其它附件
    other_annex = ForeignKey(Contract_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Contract_other_annex')  # 其它附件

    checks = GenericRelation(Check)


#项目状态变化记录
class Status_change(Model):
    business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, blank=True, default=None, related_name='Status_changes_business_opportunity')
    project_status = ForeignKey('system.Dict_item', on_delete=SET_NULL,null=True, blank=True, default=None, related_name='Status_change')
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='创建者',related_name='Status_changes_creator')

    class Meta:
        verbose_name = '项目状态变化记录'
        verbose_name_plural = verbose_name

    def __int__(self):
        return self.project_status.name

# 本周进展
class Progress_thisweek(Model):
    business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, blank=True, default=None,
                                      related_name='Progress_thisweek_business_opportunity')
    progress_record = CharField(max_length=1024, verbose_name='进展记录', null=True, blank=True)
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='创建者',
                         related_name='Progress_thisweek_creator')


    class Meta:
        verbose_name = '本周进展'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.progress_record

# 签约预测,过滤的时候根据项目状态来过滤展示在前端
class Signing_forecast(Model):
    business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, blank=True, default=None,
                                      related_name='Signing_forecast_business_opportunity')
    tax_rate = FloatField(verbose_name='税率', null=True, blank=True, default=None)
    forecast_signing_time = DateField(verbose_name='预测签约时间', null=True, blank=True)
    create_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)
    creator = ForeignKey('system.User', on_delete=CASCADE, blank=True, null=True, default=None, verbose_name='创建者',
                         related_name='Signing_forecast_creator')

    class Meta:
        verbose_name = '本周进展'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.progress_record

# 签约合同
class SigningContract(PbiInfoBaseModel):
    business_opportunity = ForeignKey(BusinessOpportunity, on_delete=CASCADE, blank=True, default=None,
                                      related_name='SigningContract_business_opportunity')
    region = JSONField(null=True, blank=True, default=None, verbose_name='区县')
    signing_date = DateField(verbose_name='签订日期', null=True, blank=True)
    total_contract_amount_including_tax = FloatField(verbose_name='合同总金额含税', null=True, blank=True)
    total_contract_amount_excluding_tax = FloatField(verbose_name='合同总金额不含税', null=True, blank=True)
    tax_rate = FloatField(verbose_name='税率', null=True, blank=True)
    construction_unit = CharField(max_length=255, verbose_name='建设方单位', null=True, blank=True)
    place_of_implementation = CharField(max_length=255, verbose_name='实施地点', null=True, blank=True)
    description = CharField(max_length=255,verbose_name='合同描述', null=True, blank=True)
    scanned_contracts_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                      related_name='SigningContract_scanned_contracts_pdf')  # 合同扫描件
    project_review_form_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                            related_name='SigningContract_project_review_form_pdf')  # 项目评审表
    project_budget_table_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                      related_name='SigningContract_project_budget_table_pdf')  # 项目预算表
    financial_review_form_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                            related_name='SigningContract_financial_review_form_pdf')  # 财务评审表
    other_pdf = ForeignKey(Pbi_Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,
                                      related_name='SigningContract_other_pdf')  # 其它附件

    class Meta:
        verbose_name = '签约合同'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 订单管理
class Order(PbiInfoBaseModel):
    #订单管理
    contract = ForeignKey(Contract, on_delete=CASCADE, blank=True, default=None, related_name='Order_contract')
    business_type = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,
                               default=None, related_name='Order_business_type')  # 专业分类
    #订单签订状态
    order_signing_status = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,related_name='Order_order_signing_status')
    # 订单执行状态
    order_execution_status = ForeignKey('system.Dict_item', on_delete=SET_NULL, null=True, blank=True,related_name='Order_order_execution_status')
    #订单金额含税
    order_amount = FloatField(verbose_name='订单金额含税', null=True, blank=True, default=0)
    #订单金额不含税
    order_amount_notax = FloatField(verbose_name='订单金额不含税', null=True, blank=True, default=0)
    #签订日期
    signing_time = DateField(verbose_name='签订日期', null=True, blank=True, default=None)
    #订单描述
    order_description = CharField(max_length=255, verbose_name='订单描述', null=True, blank=True)
    checks = GenericRelation(Check)




__all__ = [
    'Client', 'ClientCheck',
    'SupplierManufactor',
    'SupplierIntegrator',
    'ManufactorProduct',
    'CheckFlow',
]
